package com.le.tester.javaThink.fourth.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/9/17 17:53
 * description：生成的序列化检查
 */

class CircularSet {
    private int[] array;
    private int len;
    private int index = 0;

    public CircularSet(int len) {
        array = new int[len];
        this.len = len;
        for (int i = 0; i < len; i++)
            array[i] = -1;

        //长度为len,初始值皆为-1
        //System.out.println(Arrays.toString(array));
    }

    public synchronized void add(int i) {
        array[index] = i;
        index = ++index % len;

        //从array[-1,-1,-1,-1...]进行下标的替换
        //System.out.println(Arrays.toString(array));
    }

    public synchronized boolean contains(int val) {
        for (int i = 0; i < len; i++)
            if (array[i] == val)
                return true;
        return false;
    }
}

public class SerialNumberChecker {
    private static final int SIZE = 10;
    private static CircularSet serials = new CircularSet(1000);

    private static ExecutorService service = Executors.newCachedThreadPool();

    static class SerialChecker implements Runnable {

        @Override
        public void run() {
            while (true) {
                //产生的数字并不会唯一(所以加上了重锁synchronized)
                int serial = SerialNumberGenerator.nextSerialNumber();
                //从数组中匹配serial,使得产生唯一的序列数
                if (serials.contains(serial)) {
                    System.out.println("Duplicate:" + serial);
                    System.exit(0);
                }
                System.out.println("generator num is " + serial);
                serials.add(serial);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < SIZE; i++)
            service.submit(new SerialChecker());

        if (args.length > 0) {
            TimeUnit.SECONDS.sleep(new Integer(args[0]));
            System.out.println("No Duplicate deleted");
            System.exit(0);
        }
    }
}
